<?php
namespace App\Controllers\Home;
use App\Models\Diary\Diary;

/**
*	设置日记
*/
class SetDiary extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        //$this->needLogin = TRUE;
    }
	
	public function execute(){
		$info = $this->request->get('info');
		$id = (int)$this->request->get('id');
		
		if( empty($info) ){
				return \App\Libs\Views\Json::view(1, '不能为空', null);	
		}
		if( empty( $id ) ){
			//添加
			$imgData = '';
			if( $this->request->hasFiles() ){
				$imgData = \App\Libs\Helper\CommonHelper::fileUpload($this->request->getUploadedFiles());
				$imgData = $imgData[0];
			}
			if( empty( $imgData )){
				return \App\Libs\Views\Json::view(1, '图片不能为空', null);		
			}
			$diary = new Diary();
			$diary->ctime = date("Y-m-d H:i:s");
			$diary->info = $info;
			$diary->url = $imgData['uri'];
			if( $diary->save() == false ){
				return \App\Libs\Views\Json::view(1, '保存失败', null);	
			}else{
				//header("Location:/home/index.html");
				return \App\Libs\Views\Json::view(0, '保存成功', null);	
			}
		}else{
			$diary = Diary::findOne(array(
				' id = :did:',
				'bind'=>array('did'=>$id)
			));
			if( empty( $diary ) ){
				return \App\Libs\Views\Json::view(1, '日记不存在', null);	
			}	
			//修改
			$imgData = App\Libs\Helper\CommonHelper::fileUpload();
			if( !empty( $imgData ) ){
				//修改图片
				$diary->url = $imgData['uri'];
			}
			$diary->info = $info;
			if( $diary->save() == false ){
				return \App\Libs\Views\Json::view(1, '保存失败', null);	
			}else{
				//header("Location:/home/index.html");
				return \App\Libs\Views\Json::view(0, '保存成功', null);	
			}
		}
		
		
	}
}
